package com.lanou.myapp.circlepicture;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by dllo on 15/12/15.
 */
public class MyCircle extends ImageView{

    public MyCircle(Context context) {
        super(context);
    }

    public MyCircle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        //获得ImageView里存的图片
        Drawable drawable = getDrawable();
        Paint paint = new Paint();
        if(drawable != null){
            //将图片处理成图形
            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();//获得drawable里的图片
            //处理
            Bitmap b = getCircleBitmap(bitmap); //接// 收处理过的图像
            Rect rectSrc = new Rect(0,0,b.getWidth(), b.getHeight());
            Rect rectDest = new Rect(0,0,b.getWidth(),b.getHeight());
            canvas.drawBitmap(b,rectSrc,rectDest,paint);

        }else {
            //没给图片不处理，用默认方法
            super.onDraw(canvas);
        }

    }

    //获取 圆形的BipMap
    private Bitmap getCircleBitmap(Bitmap bitmap){
        Bitmap outPut = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas();
        canvas.setBitmap(outPut);  //让画布画出的图像，显示在outPut这张bitMap上
        Paint paint = new Paint(); //画笔
        paint.setAntiAlias(true); // 抗锯齿
        //矩形范围是bitMap
        RectF rect = new RectF(0,0,bitmap.getWidth(),bitmap.getHeight());
        Rect rect1 = new Rect(0,0,bitmap.getWidth(),bitmap.getHeight());

        //圆形
        canvas.drawCircle(bitmap.getHeight()/2, bitmap.getHeight()/2, bitmap.getHeight()/2, paint);
        //圆角矩形
//        canvas.drawRoundRect(rect,30,30,paint);  //放30小得角度是圆角矩形，放上面矩形的bitmap。getwidth（）/2就是圆弧
        //设置叠放模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect1, rect1, paint);
        return outPut;

        //canvas.drawBitmap(bitmap, src, dst, paint);  src是截取的图区域，dst是要显示的图区域
        //canvas.drawBitmap(bitmap, x, y, paint);  将图画到x，y坐标区域

    }

}
